<template>
  <ElForm
    v-show="getShow"
    ref="formRef"
    :model="loginData.loginForm"
    :rules="loginRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row>
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <LoginFormTitle class="w-full" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item prop="mobile">
          <el-input
            v-model="loginData.loginForm.mobile"
            :placeholder="t('login.mobileNumberPlaceholder')"
            :prefix-icon="iconCellphone"
            type="number"
            maxlength="11"
            @input="handleMobileInput"
            class="no-spinner"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item prop="smsCode">
          <el-input
            v-model="loginData.loginForm.smsCode"
            :placeholder="t('login.codePlaceholder')"
            :prefix-icon="iconCircleCheck"
            type="number"
            @input="handleSmsCodeInput"
            @keyup.enter="handleLogin"
            class="no-spinner"
          >
            <template #append>
              <span v-if="smsCodeTimer <= 0" class="getSmsCode cursor-pointer" @click="getSmsCode">
                {{ t('login.getSmsCode') }}
              </span>
              <span v-else class="getSmsCode">
                {{ smsCodeTimer }}{{ t('login.getSmsCodeLaterAgain') }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            :title="t('login.login')"
            class="w-full"
            type="primary"
            @click="handleLogin"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <XButton :title="t('login.backLogin')" class="w-full" @click="handleBackLogin" />
        </el-form-item>
      </el-col>
    </el-row>
  </ElForm>
</template>

<script setup lang="ts">
import * as authUtil from '@/utils/auth'
import * as LoginApi from '@/api/base/login'
import { LoginStateEnum, useLoginState } from './useLogin'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { ElLoading } from 'element-plus'
import type { FormRules } from 'element-plus'
import {SystemSmsSceneEnum} from "@/utils/constants";

defineOptions({ name: 'SmsCodeLoginForm' })

const { t } = useI18n()
const message = useMessage()
const formRef = ref()
const { currentRoute, push } = useRouter()
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { getLoginState, handleBackLogin } = useLoginState()
const redirect = ref('')
const loginLoading = ref(false)

const getShow = computed(() => unref(getLoginState) == LoginStateEnum.SMS_CODE_LOGIN)

const loginRules: FormRules = {
  mobile: [
    required,
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: t('rules.phone'),
      trigger: 'blur'
    }
  ],
  smsCode: [required]
}

const loginData = reactive({
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE === 'true',
  loginForm: {
    mobile: '',
    smsCode: ''
  }
})

// 组件有时会被复用，此时created(onBeforeMount)、mounted(onMounted)生命周期钩子不会被执行，beforeRouteUpdate钩子会被触发(但第一次组件加载时不会触发该钩子)
// 所以这里需要使用侦听当前路由的方式，获取redirect参数的值
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  { immediate: true }
)

let loadingInstance: Closable
const handleLogin = async () => {
  loginLoading.value = true
  try {
    let err = await formValidate(formRef)
    if (err) return
    const res = await LoginApi.smsCodeLogin({
      mobile: loginData.loginForm.mobile,
      smsCode: loginData.loginForm.smsCode
    })
    loadingInstance = ElLoading.service({
      lock: true,
      text: `${t('common.systemLoading')}...`,
      background: 'rgba(0, 0, 0, 0.7)'
    })
    authUtil.setToken(res)
    push({ path: redirect.value || '/' })
  } finally {
    loginLoading.value = false
    loadingInstance?.close()
  }
}

const smsCodeTimer = ref(0)
let timerInterval: any = undefined

const getSmsCode = async () => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
  await LoginApi.sendSmsCode({
    mobile: loginData.loginForm.mobile,
    scene: SystemSmsSceneEnum.Staff_Sms_Login
  })
  message.success(t('login.smsCodeSendMsg'))
  // 设置倒计时
  smsCodeTimer.value = 60
  timerInterval = setInterval(() => {
    smsCodeTimer.value = smsCodeTimer.value - 1
    if (smsCodeTimer.value <= 0) {
      clearInterval(timerInterval)
    }
  }, 1000)
}

const handleMobileInput = (value: string) => {
  loginData.loginForm.mobile = value.slice(0, 11)
}

const handleSmsCodeInput = (value: string) => {
  loginData.loginForm.smsCode = value.slice(0, 4)
}
</script>

<style scoped lang="scss"></style>
